package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryBrandPage(Integer page, Integer rows, String key) {
        //确保page不大于100，rows不小于5
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        //分页
        Page<Brand> brandPage = new Page<>(page, rows);
        //判断key是否存在
        boolean blank = StringUtils.isNoneBlank(key);
        //如果key不为空，需要加入查询中
        query().like(blank,"name",key)
                .or()
                .eq(blank,"letter",key)
                .page(brandPage);
        //获取集合
        List<Brand> brandList = brandPage.getRecords();
        //转换为DTO
        List<BrandDTO> brandDTOList = brandList.stream().map(BrandDTO::new).collect(Collectors.toList());
        //获取total和totalpage
        long total = brandPage.getTotal();
        long pages = brandPage.getPages();
        return new PageDTO<>(total,pages,brandDTOList);
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {
        //select * from tb_brand where id in (select brand_id from tb_category_brand where category_id = 84);
        //根据category的id从中间表中获取所有的中间表对象集合
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("category_id", id).list();
        //获取brand的id集合
        List<Long> ids = categoryBrandList.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        //查询
        List<Brand> brandList = listByIds(ids);
        //转换
        List<BrandDTO> brandDTOList = brandList.stream().map(BrandDTO::new).collect(Collectors.toList());
        return brandDTOList;
    }


    @Override
    @Transactional      //添加事务
    public void saveBrand(BrandDTO brandDTO) {
        //将BrandDTO装换
        Brand brand = brandDTO.toEntity(Brand.class);
        //将brand添加到brand表中
        boolean sb = save(brand);
        if (!sb) {
            throw new LyException(500, "新增品牌失败！");
        }
        //获取category_id 的集合
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //获取brand的id
        Long brandId = brand.getId();
       /* //创建一个新的中间表的集合
        ArrayList<CategoryBrand> categoryBrands = new ArrayList<>();
        //遍历category_id 集合
        for (Long categoryId : categoryIds) {
            //向集合中添加中间表数据
            categoryBrands.add(CategoryBrand.of(categoryId, brandId));
        }
        //向中间表添加数据
        categoryBrandService.saveBatch(categoryBrands);*/
        //用流改写
        List<CategoryBrand> categoryBrandList = categoryIds.stream().map(categoryId -> CategoryBrand.of(categoryId, brandId)).collect(Collectors.toList());
        categoryBrandService.saveBatch(categoryBrandList);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //获取brand对象
        Brand brand = brandDTO.toEntity(Brand.class);
        //更新
        boolean updateById = updateById(brand);
        //判断更新是否成功
        if (!updateById) {
            //更新失败抛出更新失败
            throw new LyException(500, "更新品牌失败！");
        }
        //更新品牌成功，需要更新中间表
        //获取brand的id
        Long brandId = brand.getId();
        //根据brand_id删除中间表的数据
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id", brandId);
        updateById = categoryBrandService.remove(queryWrapper);
        //判断更新中间表是否成功
        if (!updateById) {
            throw new LyException(500,"更新品牌失败，更新中间表失败！");
        }
        //向中间表添加数据
        //获取更新后的分类id的集合
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //获取中间表对象集合
        List<CategoryBrand> categoryBrandList = categoryIds.stream().map(categoryId -> CategoryBrand.of(categoryId, brandId)).collect(Collectors.toList());
        //添加
        categoryBrandService.saveBatch(categoryBrandList);
    }

    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        //删除brand表中数据
        boolean removeById = removeById(id);
        //判断是否删除
        if (!removeById) {
            //删除失败，报异常
            throw new LyException(500,"删除品牌失败！");
        }
        //根据brand的id，删除中间表
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<CategoryBrand>().eq("brand_id", id);
        removeById = categoryBrandService.remove(queryWrapper);
        //判断删除中间表是否成功
        if (!removeById) {
            //失败报异常
            throw new LyException(500, "删除品牌失败，删除中间表失败！");
        }
    }
}
